#pragma once

#include <functional>
#include "Socket.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"


static const uint16_t gport = 8888;

using namespace log_ns;
using server_t = std::function<std::string(std::string&)>;

class TcpServer 
{
public:
    TcpServer(server_t server, int port = gport)
        : _port(port),
          _server(server),
          _listensock(std::make_shared<TcpSocket>()),
          _isrunning(0)
    {
        _listensock->BuildListenSocket(_port);
    }

    class ThreadData
    {
    public:
        SockSPtr _sockfd;
        InetAddr _addr;
        TcpServer *_self;

        ThreadData(SockSPtr sockfd, const InetAddr& addr, TcpServer *self)
            : _sockfd(sockfd), _addr(addr), _self(self)
        {
        }
    };

    void Loop()
    {
        _isrunning = 1;
        while (_isrunning)
        {
            InetAddr client;
            SockSPtr sockfd = _listensock->Accept(&client);
            LOG(INFO, "Accept a link:%s, fd:%d\n", client.AddrStr().c_str(), sockfd->Sockfd());

            pthread_t thread;
            ThreadData *td = new ThreadData(sockfd, client, this);
            pthread_create(&thread, nullptr, Execute, td);
        }
        _isrunning = 0;
    }

    static void *Execute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);

        std::string message;
        ssize_t n = td->_sockfd->Recv(&message);

        if(n>0)
        {
            LOG(INFO, "Get a message\n");
            std::string echo = td->_self->_server(message);
            td->_sockfd->Send(echo);
            // LOG(INFO, "Send a echo: %s\n", echo.c_str());
        }

        
        
        td->_sockfd->Close();
        delete td;
        return nullptr;
    }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    SockSPtr _listensock;
    bool _isrunning;
    server_t _server;
};
